package com.atguigui.leetcode1;

/**
 * 1145.二叉树着色游戏
 * Project: leetcode
 * Package: com.atguigui.leetcode1
 * Version: 1.0
 * <p>
 * Created by WJX on 2023/2/3 10:18
 */
public class P1145BinaryTreeColoringGame {

    public static void main(String[] args) {
        Solution solution = new P1145BinaryTreeColoringGame().new Solution();
        // TO TEST
    }

    class Solution {
        TreeNode xNode;


        public boolean btreeGameWinningMove(TreeNode root, int n, int x) {
            //找到一号玩家选择的点
            findNode(root, x);
            //计算左边所有点的个数
            int leftSize = getSubtreeSize(xNode.left);
            //大于一半的数
            if (leftSize >= (n + 1) / 2) {
                return true;
            }
            int rightSize = getSubtreeSize(xNode.right);
            if (rightSize >= (n + 1) / 2) {
                return true;
            }
            //剩余的
            int remain = n - 1 - leftSize - rightSize;
            return remain >= (n + 1) / 2;
        }

        private int getSubtreeSize(TreeNode node) {

            if (node == null) {
                return 0;
            }
            return 1 + getSubtreeSize(node.left) + getSubtreeSize(node.right);
        }

        private void findNode(TreeNode node, int x) {
            if (xNode != null || node == null) {
                return;
            }
            if (node.val == x) {
                xNode = node;
                return;
            }
            findNode(node.left, x);
            findNode(node.right, x);
        }

    }

    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
